<template>
  <el-row>
    <!-- 公众号设置 -->
    <el-col :span="24">
      <!-- 预览功能 -->
      <div class="flex" v-if="openpreview"></div>
      <div class="preview" v-if="openpreview">
        <div class="previewcon">
          <img class="previewimg" :src="previewimg"/>
          <div class="previewtextbot">
            <div class="previewli"
                 :class="{'previewlione':list.length == 1,'previewlitwo':list.length == 2}"
                 v-for="(item,indx) in list" :key="indx">
              <div class="previewtianjia" v-if="previewtext == indx">
                <a class="previewaddadd"
                   v-for="(item,index) in item.list"
                   :href="item.http" target="view_window"
                   :key="index">{{ item.name }}</a>
                <div class="previewarrow" v-if="item.list.length > 0"></div>
              </div>
              <div class="previewtext" v-if="item.list.length > 0" @click="preview(item,indx)">{{ item.name }}</div>
              <a class="previewtext" v-if="item.list.length == 0"
                 :href="item.http" target="view_window"
                 @click="preview(item,indx)">{{ item.name }}</a>
            </div>
          </div>
        </div>
        <el-button type="primary" style="display: block;margin: 10px auto;" @click="out">退出预览</el-button>
      </div>
      <el-row>
        <el-col :span="24" style=" margin-top: 10px;">
          <el-row>
            <el-col :span="5" class="left">
              <img class="top" :src="top"/>
              <img class="bottom" :src="bottom"/>
              <div style="background: #F4F5F9; min-height: 438px; position: absolute; top: 63px; width: 320px;  ">
              </div>
              <div class="textbot">
                <div class="li" v-for="(item,indx) in list" :key="indx">
                  <div v-if="activeClass == indx">
                    <div class="add" @click="add(indx)">
                      <el-icon>
                        <component is="Plus"></component>
                      </el-icon>
                      <div class="arrow"></div>
                    </div>
                    <div class="tianjia">
                      <div class="addadd" v-for="(item,index) in item.list" :key="index"
                           :class="addindex == index  ? 'active':''" @click="gettem(item,index)">{{ item.name }}
                      </div>
                    </div>
                  </div>
                  <div class="text" :class="activeClass == indx ? 'active':''" @click="getItem(item,indx)">{{
                      item.name
                    }}
                  </div>
                </div>
                <div class="li" v-if="list.length < 3">
                  <div class="text" @click="addtext">
                    <el-icon>
                      <component is="Plus"></component>
                    </el-icon>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="15" style=" padding-left: 20px;">
              <el-card class="box-card right">
                <div slot="header" class="clearfix">
                  <span>{{ input }}</span>
                  <el-button style="float: right; padding: 3px 0" type="text" @click="delet">删除子菜单</el-button>
                </div>
                <div style="display: flex;">
                  <label style="line-height: 34px; width:80px;">菜单名称</label>
                  <el-input v-model="input" placeholder="请输入内容" style="width:70%;"></el-input>
                </div>
                <p style="color: #9A8D8D;margin-left: 80px;">一级菜单最多6个汉字或12个字母，二级菜单最多7个汉字或14个字母，多出来的部分将会以“...”代替</p>
                <div style="display: flex;">
                  <label style="line-height: 34px; width:80px;">菜单类型</label>
                  <el-radio-group v-model="menuType">
                    <el-radio-button label="view">网页</el-radio-button>
                    <el-radio-button label="click">点击</el-radio-button>
                    <el-radio-button label="miniprogram">小程序</el-radio-button>
                  </el-radio-group>
                </div>
                <p style="color: #9A8D8D;margin-left: 80px;">网页类型(页面地址必填)，点击类型，小程序类型(页面地址必填)</p>
                <div style="display: flex;" v-show="contentFlag">
                  <label style="line-height: 34px; width:80px;">菜单内容</label>
                </div>
                <p v-show="contentFlag" style="color: #9A8D8D;margin-left: 30px;">订阅者点击该子菜单会跳到以下链接</p>
                <div style="display: flex; padding:0 30px;" v-show="contentFlag">
                  <label style="line-height: 34px; width:65px;padding-right: 5px">页面地址</label>
                  <el-input
                      type="textarea"
                      :autosize="{ minRows: 3, maxRows: 6}"
                      v-model="inputhttp" placeholder="请输入地址" style="width:75%;"></el-input>
                </div>
                <el-button v-show="contentFlag" type="text" style="margin-left: 100px;" @click="openMedia">
                  从公众号图文消息中选择
                </el-button>
                <div class="clearfix" style="margin-top: 130px;width: 100%;text-align: center">
                  <el-button style="margin: 10px auto;" @click="open">打开预览</el-button>
                  <el-button type="primary" style="margin: 10px auto;" @click="save">保存并发布
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-col>
    <el-dialog
        title="选择素材"
        v-model="dialogVisible"
        width="70%">
      <el-table v-loading="loading"
                :data="table.rows"
                border
                stripe
                style="width: 100%;margin-bottom: 10px">
        <el-table-column
            prop="mediaId"
            label="素材编号"
            width="300"
            align="center">
        </el-table-column>
        <el-table-column
            prop="updateTime"
            label="创建时间"
            width="180"
            align="center">
        </el-table-column>
        <el-table-column
            prop="op"
            label="详情"
            align="center">
          <template #default="scope">
            <el-row v-for="(item,index) in scope.row.content.articles" :key="index">
              <el-col :span="9"
                      style="white-space: nowrap; overflow: hidden;  text-overflow: ellipsis;color: #E6A23C">
                标题： <a href="#" :title="item.title" style="color: #E6A23C;cursor: auto;text-decoration: none"
                       target="_blank">{{ item.title }}</a>
              </el-col>
              <el-col :span="12"
                      style="white-space: nowrap; overflow: hidden;  text-overflow: ellipsis;color: #409EFF">
                地址：<a :href="item.url" :title="item.url" style="color: #409EFF" target="_blank">{{ item.url }}</a>
              </el-col>
              <el-col :span="3" style="">
                <el-button type="primary" size="mini" @click="confirmMedia(item.url)">确认
                </el-button>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="table.pageNumber"
          :page-sizes="[5, 10, 20, 30, 50]"
          :page-size="table.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="table.total">
      </el-pagination>
      <template #footer>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
      </template>
    </el-dialog>

  </el-row>

</template>
<script>

import {WechatMedia, WechatMenu} from "@/utils/wechat";
import mobile from "@/assets/bg_mobile49d02c.png";
import headerImg from "@/assets/bg_mobile_head_default49d02c.png";
import footerImg from "@/assets/bg_mobile_foot_default49d02c.png";


export default {
  name: "wechat-menus",
  data() {
    return {
      queryParams: {},
      loading: false,
      dialogVisible: false,
      disable: false,
      table: {
        rows: [],
        total: 0,
        pageSize: 10,
        pageNumber: 1,
      },
      idSeq: 0,

      previewimg: mobile,
      previewtext: 0,
      openpreview: false,
      top: headerImg,
      bottom: footerImg,
      activeClass: 0,
      addindex: -1,
      input: '',
      inputhttp: '',
      menuType: null,
      contentFlag: true,
      shu: 6,
      id: 1,
      list: [
        {
          name: '菜单一',
          http: '',
          id: 1,
          type: null,
          list: [{'name': '我是1', http: '', id: 4, type: null}]
        },
        {
          name: '菜单二',
          http: '',
          id: 2,
          type: null,
          list: [{'name': '我是2', http: '', id: 5, type: null}]
        },
        {
          name: '菜单三',
          http: '',
          id: 3,
          type: null,
          list: [{'name': '我是3', http: '', id: 6, type: null}]
        }
      ],
      listlist: [],

    }
  },
  async mounted() {
    this.rech()
    await this.loadMenu()
    this.input = this.list[0].name
    this.inputhttp = this.list[0].http
  },
  watch: {
    // 如果 `input` 发生改变，这个函数就会运行
    input: function () {
      for (var i = 0; i < this.list.length; i++) {
        for (var j = 0; j < this.list[i].list.length; j++) {
          if (this.list[i].list[j].id === this.id) {
            this.list[i].list[j].name = this.input
          }
        }
        if (this.list[i].id === this.id) {
          this.list[i].name = this.input
        }
      }
      this.rech()
      // 限制名字个数
      var temp = 0
      for (var k = 0; k < this.input.length; k++) {
        if (/[\u4e00-\u9fa5]/.test(this.input[k])) {
          temp += 2
        } else {
          temp++
        }
        if (temp > 12) {
          // this.input.substr(0, k)
          this.$message({
            message: '仅支持中英文和数字，字数不超过6个汉字或12个字母',
            type: 'warning'
          })
          this.disable = true
        } else {
          this.disable = false
        }
      }
    },
    inputhttp: function () {
      for (var i = 0; i < this.list.length; i++) {
        for (var j = 0; j < this.list[i].list.length; j++) {
          if (this.list[i].list[j].id === this.id) {
            this.list[i].list[j].http = this.inputhttp
          }
        }
        if (this.list[i].id === this.id) {
          this.list[i].http = this.inputhttp
        }
      }
      this.rech()
    },
    menuType: function () {
      if ("click" == this.menuType) {
        this.inputhttp = '';
        this.contentFlag = false;
      } else {
        this.contentFlag = true;
      }
      for (var i = 0; i < this.list.length; i++) {
        for (var j = 0; j < this.list[i].list.length; j++) {
          if (this.list[i].list[j].id === this.id) {
            this.list[i].list[j].type = this.menuType
          }
        }
        if (this.list[i].id === this.id) {
          this.list[i].type = this.menuType
        }
      }
      this.rech()
    }
  },
  methods: {
    out() {
      this.openpreview = false
    },
    open() {
      this.openpreview = true
    },
    preview(item, index) {
      this.previewtext = index
    },
    //   父元素
    getItem(item, index) {
      this.addindex = -1
      this.activeClass = index  // 把当前点击元素的index，赋值给activeClass
      this.input = item.name
      this.inputhttp = item.http
      this.id = item.id
      this.menuType = item.type
      this.rech()
    },
    // 子元素
    gettem(item, index) {
      this.addindex = index
      console.log(item)
      this.input = item.name
      this.inputhttp = item.http
      this.id = item.id
      this.menuType = item.type
      this.rech()
    },
    // 增加
    add(index) {
      this.shu++
      this.list[index].list.push({
        'name': '子菜单' + this.shu, http: '', id: this.shu
      })
      this.rech()
    },
    addtext() {
      this.shu++
      this.list.push({
        'name': '菜单' + this.shu, http: '', id: this.shu, list: []
      })
      this.rech()
    },
    // 删除
    delet() {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        for (var i = 0; i < this.list.length; i++) {
          for (var j = 0; j < this.list[i].list.length; j++) {
            if (this.list[i].list[j].id === this.id) {
              this.list[i].list.splice(j, 1)
              this.addindex = -1
              this.rech()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }
          }
          if (this.list[i].id === this.id) {
            this.list.splice(i, 1)
            this.activeClass = -1
            this.rech()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    rech() {
      this.listlist = []
      this.list.forEach(item => {
        this.listlist.push({
          name: item.name,
          http: item.http
        })
        item.list.forEach(item => {
          this.listlist.push({
            name: item.name,
            http: item.http
          })
        })
      })
    },
    async loadMenu() {
      let res = await WechatMenu.get()
      let menu = {...res.data.menu}
      if (menu.buttons) {
        menu.subButtons = menu.buttons
      }
      this.list = this.mapMenuToList(menu).list;
    },
    async save() {
      let data1 = this.mapListToMenu({
        name: "root",
        list: this.list
      }).subButtons;
      console.log(data1)
      let res = await WechatMenu.create({buttons: data1})
      if (res.code === 0) {
        this.$message({
          message: '菜单创建成功',
          type: 'success'
        })
      } else {
        this.$message({
          message: '菜单创建失败',
          type: 'error'
        })
      }
    },
    mapListToMenu(org) {
      const haveChildren = Array.isArray(org.list) && org.list.length > 0;
      return {
        //分别将我们查询出来的值做出改变他的key
        type: org.type,
        name: org.name,
        url: org.http,
        key: org.id,
        //判断它是否存在子集，若果存在就进行再次进行遍历操作，知道不存在子集便对其他的元素进行操作
        subButtons: haveChildren ? org.list.map(i => this.mapListToMenu(i)) : []
      };
    },
    mapMenuToList(menu) {
      const haveChildren = Array.isArray(menu.subButtons) && menu.subButtons.length > 0;
      return {
        //分别将我们查询出来的值做出改变他的key
        id: this.idSeq++,
        name: menu.name,
        http: menu.url,
        type: menu.type,
        //判断它是否存在子集，若果存在就进行再次进行遍历操作，知道不存在子集便对其他的元素进行操作
        list: haveChildren ? menu.subButtons.map(i => this.mapMenuToList(i)) : []
      };
    },
    openMedia() {
      this.dialogVisible = true
      this.query()
    },
    async query() {
      await WechatMedia.search(this.table, {})
    },
    handleSizeChange(val) {
      this.table.pageSize = val
      this.query()
    },
    handleCurrentChange(val) {
      this.table.pageNumber = val
      this.query()
    },
    confirmMedia(url) {
      this.inputhttp = url
      this.dialogVisible = false
    },
    /*    menuTypeChange(env){
          if("click" == env){
            this.inputhttp = '';
            this.contentFlag = false;
          }else {
            this.contentFlag = true;
          }
        }*/
  }
}
</script>


<style scoped>
* {
  /*css页面点击文字出现蓝色底色去掉方法*/
  -moz-user-select: none; /*火狐*/
  -webkit-user-select: none; /*webkit浏览器*/
  -ms-user-select: none; /*IE10*/
  -khtml-user-select: none; /*早期浏览器*/
  user-select: none;
}

.flex {
  position: fixed;
  background: #000000;
  opacity: 0.5;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  z-index: 99;
}


.preview {
  position: fixed;
  top: 5%;
  left: 45%;
  z-index: 99;
}

.previewcon {
  position: relative;
}

.previewimg {
  width: 80%;
  height: auto;
  margin: 0 10%;
}

.previewtextbot {
  position: absolute;
  bottom: 79px;
  left: 88px;
  width: 100%;
}

.previewtext {
  height: 29px;
  display: block;
  text-decoration: none;
  /*去掉默认下滑线
   color:#999; /*设置默认颜色*/
}

.previewli {
  float: left;
  width: 59px;
  line-height: 29px;
  border: 1px solid #E7E7EB;
  background: #FAFAFA;
  text-align: center;
  cursor: pointer;
  color: #999;
  position: relative;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.previewlione {
  width: 233px !important;
}

.previewlitwo {
  width: 117px !important;
}

.previewtianjia {
  position: absolute;
  bottom: 44px;
  width: 100%;
  line-height: 29px;
  background: #FAFAFA;
}


.previewaddadd {
  width: 100%;
  line-height: 29px;
  border: 1px solid #E7E7EB;
  background: #fff;
  height: 29px;
  display: block;
  text-decoration: none;
  color: #999;
  font-size: 12px;
}

.previewarrow {
  position: absolute;
  bottom: -15px;
  left: 44%;
  /* 圆角的位置需要细心调试哦 */
  width: 0;
  height: 0;
  font-size: 0;
  border: solid 8px;
  border-color: #fff #E6E6E6 #E6E6E6 #E6E6E6;
}

.warning {
  border: 1px solid #91d5ff;
  background-color: #e6f7ff;
  padding: 5px 20px;
}


.on {
  text-align: right;
  float: right;
  color: #1890ff;
}


.tips {
  color: #1890ff;
  font-size: 20px;
  margin-right: 10px;
}


.left {
  min-width: 390px;
  min-height: 550px;
  position: relative;
  padding-left: 40px;
}


.top {
  position: absolute;
  top: 0px;
}


.bottom {
  position: absolute;
  bottom: 0px;
}


.textbot {
  position: absolute;
  bottom: -3px;
  left: 82px;
  width: 100%;
}


.active {
  border: 1px solid #44B549 !important;
  color: #44B549 !important;
}


.li {
  float: left;
  width: 91px;
  font-size: 13px;
  line-height: 51px;
  border: 1px solid #E7E7EB;
  background: #FAFAFA;
  text-align: center;
  cursor: pointer;
  color: #999;
  position: relative;
}

.text {
  height: 50px;
}

.text:hover {
  color: #000;
}


.add {
  position: absolute;
  bottom: 65px;
  width: 100%;
  line-height: 48px;
  border: 1px solid #E7E7EB;
  background: #FAFAFA;
}

.arrow {
  position: absolute;
  bottom: -16px;
  left: 36px;
  /* 圆角的位置需要细心调试哦 */
  width: 0;
  height: 0;
  font-size: 0;
  border: solid 8px;
  border-color: #fff #F4F5F9 #F4F5F9 #F4F5F9;
}

.tianjia {
  position: absolute;
  bottom: 115px;
  width: 100%;
  line-height: 48px;
  background: #FAFAFA;
}


.addadd {
  width: 100%;
  line-height: 48px;
  border: 1px solid #E7E7EB;
  background: #FAFAFA;
  height: 48px;
}


.right {
  background: #F4F5F9;
  min-height: 550px;
}


</style>
